<?php if(!class_exists("View", false)) exit("no direct access allowed");?><main class="container mx-auto px-4 pt-24 pb-16 flex">
    <?php include $_view_obj->compile("left_menu.html"); ?>

    <!-- 部门列表 -->
    <section class="mb-10 w-3/4 ml-4 bg-white rounded-xl shadow-sm p-4">
        <div class="flex justify-between items-center mb-4">
            <h2 class="text-xl font-bold text-dark">部门列表</h2>
            <div class="flex items-center space-x-4" id="dept-info">
                <button class="btn btn-primary" id="add-dept-button">添加部门</button>
            </div>
        </div>
        <!-- 新增滚动容器 -->
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <input type="checkbox" id="select-all-depts">
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            ID
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            部门名称
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            上级部门
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            路径
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            层级
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            排序
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            职位
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            职能
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            负责人
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            操作
                        </th>
                    </tr>
                </thead>
                <tbody id="dept-list" class="bg-white divide-y divide-gray-200">
                    <!-- 部门数据将通过 JavaScript 动态添加 -->
                </tbody>
            </table>
        </div>
        <div class="flex justify-center mt-4" id="dept-pagination">
            <!-- 分页按钮将通过 JavaScript 动态添加 -->
        </div>
    </section>

    <!-- 添加部门弹出框 -->
    <div id="add-dept-modal" class="fixed inset-0 z-50 hidden bg-black bg-opacity-50 flex items-center justify-center">
        <div class="bg-white rounded-xl shadow-2xl p-8 w-96 relative">
            <span id="close-add-dept-modal" class="absolute top-3 right-3 text-gray-600 hover:text-gray-800 cursor-pointer">
                <i class="fa fa-times"></i>
            </span>
            <h2 class="text-2xl font-bold text-dark mb-6 text-center">添加部门</h2>
            <form id="add-dept-form">
                <div class="mb-6">
                    <label for="add-dept-name" class="block text-sm font-medium text-gray-700 mb-1">部门名称</label>
                    <input type="text" id="add-dept-name" class="input-field w-full" required>
                </div>
                <div class="mb-6">
                    <label for="add-dept-parent" class="block text-sm font-medium text-gray-700 mb-1">上级部门</label>
                    <select id="add-dept-parent" class="input-field w-full">
                        <!-- 部门选项将通过 JavaScript 动态添加 -->
                    </select>
                </div>
                <div class="mb-6">
                    <label for="add-dept-position" class="block text-sm font-medium text-gray-700 mb-1">职位</label>
                    <input type="text" id="add-dept-position" class="input-field w-full">
                </div>
                <div class="mb-6">
                    <label for="add-dept-function" class="block text-sm font-medium text-gray-700 mb-1">职能</label>
                    <input type="text" id="add-dept-function" class="input-field w-full">
                </div>
                <div class="mb-6">
                    <label for="add-dept-manager" class="block text-sm font-medium text-gray-700 mb-1">负责人</label>
                    <input type="text" id="add-dept-manager" class="input-field w-full">
                </div>
                <div class="flex justify-center space-x-6">
                    <button type="button" id="cancel-add-dept" class="btn-secondary">取消</button>
                    <button type="submit" id="submit-add-dept" class="btn-primary">提交</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 编辑部门弹出框 -->
    <div id="edit-dept-modal" class="fixed inset-0 z-50 hidden bg-black bg-opacity-50 flex items-center justify-center">
        <div class="bg-white rounded-xl shadow-2xl p-8 w-1/2 relative"> <!-- 调整弹框宽度 -->
            <span id="close-edit-dept-modal" class="absolute top-3 right-3 text-gray-600 hover:text-gray-800 cursor-pointer">
                <i class="fa fa-times"></i>
            </span>
            <h2 class="text-2xl font-bold text-dark mb-6 text-center">编辑部门</h2>
            <form id="edit-dept-form">
                <input type="hidden" id="edit-dept-id">
                <div class="mb-6">
                    <label for="edit-dept-name" class="block text-sm font-medium text-gray-700 mb-1">部门名称</label>
                    <input type="text" id="edit-dept-name" class="input-field w-full" required>
                </div>
                <div class="mb-6">
                    <label for="edit-dept-parent" class="block text-sm font-medium text-gray-700 mb-1">上级部门</label>
                    <select id="edit-dept-parent" class="input-field w-full">
                        <!-- 部门选项将通过 JavaScript 动态添加 -->
                    </select>
                </div>
                <div class="mb-6">
                    <label for="edit-dept-position" class="block text-sm font-medium text-gray-700 mb-1">职位</label>
                    <input type="text" id="edit-dept-position" class="input-field w-full">
                </div>
                <div class="mb-6">
                    <label for="edit-dept-function" class="block text-sm font-medium text-gray-700 mb-1">职能</label>
                    <input type="text" id="edit-dept-function" class="input-field w-full">
                </div>
                <div class="mb-6">
                    <label for="edit-dept-manager" class="block text-sm font-medium text-gray-700 mb-1">负责人</label>
                    <input type="text" id="edit-dept-manager" class="input-field w-full">
                </div>
                <div class="flex justify-center space-x-6">
                    <button type="button" id="cancel-edit-dept" class="btn-secondary">取消</button>
                    <button type="submit" id="submit-edit-dept" class="btn-primary">提交</button>
                </div>
            </form>
        </div>
    </div>
</main>


<script>
    const itemsPerPage = 5;
    let currentPage = 1;
    let totalDepts = 0;

    // 构建部门树形结构
function buildDeptTree(depts) {
    const tree = {};
    const idMap = {};

    depts.forEach(dept => {
        idMap[dept.id] = { ...dept, children: [] };
    });

    depts.forEach(dept => {
        if (dept.parent) {
            if (idMap[dept.parent]) {
                idMap[dept.parent].children.push(idMap[dept.id]);
            }
        } else {
            tree[dept.id] = idMap[dept.id];
        }
    });

    return tree;
}

// 递归生成树形选项
function generateTreeOptions(tree, level = 0) {
    let options = '';
    for (const id in tree) {
        const dept = tree[id];
        const indent = '&nbsp;&nbsp;&nbsp;&nbsp;'.repeat(level);
        options += `<option value="${dept.id}">${indent}${dept.name}</option>`;
        if (dept.children.length > 0) {
            const childTree = buildDeptTree(dept.children);
            options += generateTreeOptions(childTree, level + 1);
        }
    }
    return options;
}

// 获取部门列表
function getDeptList() {
    const url = '<?php echo url(array('c'=>"system", 'a'=>"GetDeptList", ));?>';
    $.ajax({
        url: url,
        method: 'GET',
        dataType: 'json',
        success: function (response) {
            const depts = response.data;
            const addDeptSelect = $('#add-dept-parent');
            const editDeptSelect = $('#edit-dept-parent');
            addDeptSelect.empty();
            editDeptSelect.empty();
            
            const tree = buildDeptTree(depts);
            const options = generateTreeOptions(tree);

            // 添加调试信息
            console.log('生成的选项:', options);

            addDeptSelect.append(options);
            editDeptSelect.append(options);
        },
        error: function (error) {
            console.error('获取部门列表失败:', error);
        }
    });
}

// 显示部门列表
function displayDepts() {
    const url = '<?php echo url(array('c'=>"system", 'a'=>"GetDeptListForPage", ));?>?start=' + currentPage + '&limit=' + itemsPerPage;

    $.ajax({
        url: url,
        method: 'GET',
        dataType: 'json',
        success: function (response) {
            const depts = response.data.list;
            totalDepts = response.data.pager.total_count;
            console.log(totalDepts);

            const deptList = $('#dept-list');
            deptList.empty();

            depts.forEach(dept => {
                const row = $('<tr>');
                row.html(`
                    <td class="px-6 py-4 whitespace-nowrap">
                        <input id="${dept.id}" type="checkbox">
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">${dept.id}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${dept.name}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${dept.parentName || '无'}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${dept.path}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${dept.grade}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${dept.order}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${dept.position}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${dept.function}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${dept.manager}</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <button class="btn btn-info mr-2" onclick="editDept(${dept.id})">编辑</button>
                        <button class="btn btn-danger" onclick="deleteDept(${dept.id})">删除</button>
                    </td>
                `);
                deptList.append(row);
            });

            displayPagination();
        },
        error: function (error) {
            console.error('请求数据失败:', error);
        }
    });
}

    // 显示分页导航
    function displayPagination() {
        const totalPages = Math.ceil(totalDepts / itemsPerPage);
        const pagination = $('#dept-pagination');
        pagination.empty();

        const maxVisiblePages = 5; // 最大可见页码数
        const startPage = Math.max(currentPage - Math.floor(maxVisiblePages / 2), 1);
        const endPage = Math.min(startPage + maxVisiblePages - 1, totalPages);

        // 上一页按钮
        if (currentPage > 1) {
            const prevButton = $('<button>');
            prevButton.text('上一页');
            prevButton.addClass('px-3 py-1 mx-1 border rounded');
            prevButton.on('click', function () {
                currentPage--;
                displayDepts();
            });
            pagination.append(prevButton);
        }

        // 页码按钮
        for (let i = startPage; i <= endPage; i++) {
            const button = $('<button>');
            button.text(i);
            button.addClass('px-3 py-1 mx-1 border rounded');
            if (i === currentPage) {
                button.addClass('bg-primary text-white');
            }
            button.on('click', function () {
                currentPage = i;
                displayDepts();
            });
            pagination.append(button);
        }

        // 下一页按钮
        if (currentPage < totalPages) {
            const nextButton = $('<button>');
            nextButton.text('下一页');
            nextButton.addClass('px-3 py-1 mx-1 border rounded');
            nextButton.on('click', function () {
                currentPage++;
                displayDepts();
            });
            pagination.append(nextButton);
        }
    }

    // 打开添加部门弹出框
    const addDeptButton = $('#add-dept-button');
    const addDeptModal = $('#add-dept-modal');
    const closeAddDeptModal = $('#close-add-dept-modal');
    const cancelAddDept = $('#cancel-add-dept');

    addDeptButton.on('click', function () {
        addDeptModal.removeClass('hidden');
        getDeptList();
    });

    closeAddDeptModal.on('click', function () {
        addDeptModal.addClass('hidden');
    });

    cancelAddDept.on('click', function () {
        addDeptModal.addClass('hidden');
    });

    // 提交添加部门表单
    const addDeptForm = $('#add-dept-form');
    addDeptForm.on('submit', function (e) {
        e.preventDefault();
        const name = $('#add-dept-name').val();
        const parent = $('#add-dept-parent').val();
        const position = $('#add-dept-position').val();
        const func = $('#add-dept-function').val();
        const manager = $('#add-dept-manager').val();

        $.ajax({
            url: '<?php echo url(array('c'=>"system", 'a'=>"AddDept", ));?>',
            method: 'POST',
            data: {
                name: name,
                parent: parent,
                position: position,
                function: func,
                manager: manager
            },
            dataType: 'json',
            success: function (response) {
                addDeptModal.addClass('hidden');
                displayDepts();
                addDeptForm[0].reset();
            },
            error: function (error) {
                console.error('添加部门失败:', error);
            }
        });
    });

    // 打开编辑部门弹出框
    function editDept(id) {
        const url = `<?php echo url(array('c'=>"system", 'a'=>"GetDept", ));?>?id=${id}`;

        $.ajax({
            url: url,
            method: 'GET',
            dataType: 'json',
            success: function (response) {
                const dept = response.data;
                const editDeptModal = $('#edit-dept-modal');
                const editDeptId = $('#edit-dept-id');
                const editDeptName = $('#edit-dept-name');
                const editDeptParent = $('#edit-dept-parent');
                const editDeptPosition = $('#edit-dept-position');
                const editDeptFunction = $('#edit-dept-function');
                const editDeptManager = $('#edit-dept-manager');

                editDeptId.val(dept.id);
                editDeptName.val(dept.name);
                editDeptParent.val(dept.parent);
                editDeptPosition.val(dept.position);
                editDeptFunction.val(dept.function);
                editDeptManager.val(dept.manager);

                editDeptModal.removeClass('hidden');

                getDeptList();
            },
            error: function (error) {
                console.error('获取部门信息失败:', error);
            }
        });
    }

    // 关闭编辑部门弹出框
    const closeEditDeptModal = $('#close-edit-dept-modal');
    const cancelEditDept = $('#cancel-edit-dept');

    closeEditDeptModal.on('click', function () {
        const editDeptModal = $('#edit-dept-modal');
        editDeptModal.addClass('hidden');
    });

    cancelEditDept.on('click', function () {
        const editDeptModal = $('#edit-dept-modal');
        editDeptModal.addClass('hidden');
    });

    // 提交编辑部门表单
    const editDeptForm = $('#edit-dept-form');
    editDeptForm.on('submit', function (e) {
        e.preventDefault();
        const id = parseInt($('#edit-dept-id').val());
        const name = $('#edit-dept-name').val();
        const parent = $('#edit-dept-parent').val();
        const position = $('#edit-dept-position').val();
        const func = $('#edit-dept-function').val();
        const manager = $('#edit-dept-manager').val();

        $.ajax({
            url: '<?php echo url(array('c'=>"system", 'a'=>"UpdateDept", ));?>',
            method: 'POST',
            data: {
                id: id,
                name: name,
                parent: parent,
                position: position,
                function: func,
                manager: manager
            },
            dataType: 'json',
            success: function (response) {
                const editDeptModal = $('#edit-dept-modal');
                editDeptModal.addClass('hidden');
                displayDepts();
                editDeptForm[0].reset();
            },
            error: function (error) {
                console.error('编辑部门失败:', error);
            }
        });
    });

    // 删除部门
    function deleteDept(id) {
        if (confirm('确定要删除该部门吗？')) {
            $.ajax({
                url: `<?php echo url(array('c'=>"system", 'a'=>"DeleteDept", ));?>?id=${id}`,
                method: 'DELETE',
                dataType: 'json',
                success: function (response) {
                    displayDepts();
                },
                error: function (error) {
                    console.error('删除部门失败:', error);
                }
            });
        }
    }

    // 初始化显示部门列表和部门下拉框
    
    displayDepts();
</script>